import { HCode } from "./../common/code";
import { ArgumentMetadata, HttpException, Injectable, PipeTransform } from "@nestjs/common";
import { plainToClass } from "class-transformer";
import { validate } from "class-validator";
import * as _ from "lodash";

@Injectable()
export class HValidationPipe implements PipeTransform<any> {
  async transform(value: any, metadata: ArgumentMetadata) {
      const { metatype } = metadata;
      // 如果不是五大基础类型，不进行校验
      if (!metatype || !this.toValidate(metatype)) {
        return value;
      }

      const object = plainToClass(metatype, value);
      const errors = await validate(object);
      // TODO: 校验错误日志记录
      if (errors.length > 0) {
        let errorMessage = null;
        // 遍历所有的校验错误信息， 输出到响应
        // errorMessage = errors.map(item => {
        //   return {
        //     currentValue: item.value,
        //     errorMessage: Object.values(item.constraints)[0],
        //     property: item.property
        //   }
        // })
        // 只输出第一条错误信息
        errorMessage = `${_.first(Object.values(_.first(errors).constraints))}`

        throw new HttpException(errorMessage, HCode.invalidInput);
      }
      return value;
  }

  private toValidate(metatype: any): boolean {
    const types = [String, Boolean, Number, Array, Object];
    return !types.includes(metatype);
  }
}